package com.ljm.file.handle;

import com.ljm.common.dto.BaseResult;
import com.ljm.common.util.ResultUtil;
import com.ljm.file.common.EditorResponseDto;
import com.ljm.file.properties.BucketType;
import com.ljm.file.record.api.SysFileApi;
import com.ljm.file.record.dto.SysFileDto;
import com.ljm.file.recycle.dto.SysFileRecycleDto;
import com.ljm.file.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author: ChenHuaMing
 * @Date: 2020/9/28 12:07
 * @Description: 文件处理
 */
@Api(tags = "文件处理")
@RestController
@RequestMapping("/file/handleFile")
public class FileHandleController {
    @Resource
    private FileService fileService;
    @Resource
    private SysFileApi sysFileApi;

    @ApiOperation(value = "富文本上传")
    @RequestMapping(value = "/editorUpload",method = RequestMethod.POST)
    public EditorResponseDto editorUpload(@RequestParam(required = false) @ApiParam("系统标识") String fdSys,
                                          @RequestParam(required = false) @ApiParam("模块标识") String fdModule,
                                          @RequestParam(required = false) @ApiParam("业务唯一标识") String fdSectionId,
                                          @RequestParam @ApiParam("文件") MultipartFile file) throws IOException {
        fdSys= StringUtils.isEmpty(fdSys)?"default_sys":fdSys;
        fdModule= StringUtils.isEmpty(fdModule)?"common_editor":fdModule;
        fdSectionId= StringUtils.isEmpty(fdSectionId)?UUID.randomUUID().toString():fdSectionId;
        String originalFullFilename = file.getOriginalFilename();
        String suffix=originalFullFilename.substring(originalFullFilename.lastIndexOf(".")+1);
        String originalFilename=originalFullFilename.substring(0,originalFullFilename.lastIndexOf("."));
        String ossFileName= UUID.randomUUID().toString();
        String ossFullFileName=ossFileName+"."+suffix;
        fileService.fileUpload(BucketType.publicBucket,fdModule,ossFullFileName,file.getInputStream());
        String downLoadUrl = fileService.getDownLoadUrl(BucketType.publicBucket,fdModule, ossFullFileName,null);
        SysFileDto sysFileDto=new SysFileDto(originalFilename,ossFileName,suffix,file.getSize(),false,fdModule,downLoadUrl,fdSys,fdModule,fdSectionId);
        sysFileApi.saveFileRecord(sysFileDto);

        List<EditorResponseDto.DetailDto> data=new ArrayList<>();
        data.add(EditorResponseDto.DetailDto.builder().url(downLoadUrl).build());

        return EditorResponseDto.EditorResponseDtoBuilder.createEditorResponseDto()
                .withErrno(0)
                .withData(data)
                .build();
    }

    @ApiOperation(value = "公开上传")
    @RequestMapping(value = "/publicUpload",method = RequestMethod.POST)
    public BaseResult publicUpload(@RequestParam @ApiParam("系统标识") String fdSys,
                                   @RequestParam @ApiParam("模块标识") String fdModule,
                                   @RequestParam @ApiParam("业务唯一标识") String fdSectionId,
                                   @RequestParam @ApiParam("文件") MultipartFile file) throws IOException {
        String originalFullFilename = file.getOriginalFilename();
        String suffix=originalFullFilename.substring(originalFullFilename.lastIndexOf(".")+1);
        String originalFilename=originalFullFilename.substring(0,originalFullFilename.lastIndexOf("."));
        String ossFileName= UUID.randomUUID().toString();
        String ossFullFileName=ossFileName+"."+suffix;
        fileService.fileUpload(BucketType.publicBucket,fdModule,ossFullFileName,file.getInputStream());
        String downLoadUrl = fileService.getDownLoadUrl(BucketType.publicBucket,fdModule, ossFullFileName,null);
        SysFileDto sysFileDto=new SysFileDto(originalFilename,ossFileName,suffix,file.getSize(),false,fdModule,downLoadUrl,fdSys,fdModule,fdSectionId);
        sysFileApi.saveFileRecord(sysFileDto);
        return ResultUtil.success();
    }

    @ApiOperation(value = "私密上传")
    @RequestMapping(value = "/secrecyUpload",method = RequestMethod.POST)
    public BaseResult secrecyUpload(@RequestParam @ApiParam("系统标识") String fdSys,
                                   @RequestParam @ApiParam("模块标识") String fdModule,
                                   @RequestParam @ApiParam("业务唯一标识") String fdSectionId,
                                   @RequestParam @ApiParam("文件") MultipartFile file) throws IOException {
        String originalFullFilename = file.getOriginalFilename();
        String suffix=originalFullFilename.substring(originalFullFilename.lastIndexOf(".")+1);
        String originalFilename=originalFullFilename.substring(0,originalFullFilename.lastIndexOf("."));
        String ossFileName= UUID.randomUUID().toString();
        String ossFullFileName=ossFileName+"."+suffix;
        fileService.fileUpload(BucketType.secrecyBucket,fdModule,ossFullFileName,file.getInputStream());
        SysFileDto sysFileDto=new SysFileDto(originalFilename,ossFileName,suffix,file.getSize(),true,fdModule,null,fdSys,fdModule,fdSectionId);
        sysFileApi.saveFileRecord(sysFileDto);
        return ResultUtil.success();
    }

    @ApiOperation(value = "获取下载链接")
    @RequestMapping(value = "/getDownLoadLink",method = RequestMethod.GET)
    public BaseResult getDownLoadLink(@RequestParam @ApiParam("文件id")String ossFileId,
                                      @RequestParam @ApiParam("是否私密文件")Boolean isSecrecy){
        SysFileDto fileInfo = sysFileApi.getFileInfoByOssFileId(ossFileId);
        if(null==fileInfo){
            return ResultUtil.error("文件id不正确,找不到文件对应信息");
        }
        String downloadUrl=fileService.getDownLoadUrl(isSecrecy?BucketType.secrecyBucket:BucketType.publicBucket,
                fileInfo.getStoragePath(),
                fileInfo.getOssFileId()+"."+fileInfo.getFileSuffix(),
                isSecrecy?1000L*60*5:null);
        return ResultUtil.successData(downloadUrl);
    }

    @ApiOperation(value = "下载文件")
    @RequestMapping(value = "/downloadFile",method = RequestMethod.GET)
    public void downloadFile(@RequestParam @ApiParam("文件id")String ossFileId, HttpServletResponse response) throws IOException {
        SysFileDto fileInfo = sysFileApi.getFileInfoByOssFileId(ossFileId);
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileInfo.getOriginFileName()+"."+fileInfo.getFileSuffix());
        ServletOutputStream outputStream = response.getOutputStream();
        fileService.downLoadObjectToOutputStream(fileInfo.getFileType()?BucketType.secrecyBucket:BucketType.publicBucket,
                fileInfo.getStoragePath(),
                fileInfo.getOssFileId() + "." + fileInfo.getFileSuffix(),outputStream);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
    }

    @ApiOperation(value = "下载文件")
    @RequestMapping(value = "/downloadFileInRecycle",method = RequestMethod.GET)
    public void downloadFileInRecycle(@RequestParam @ApiParam("文件id")String ossFileId, HttpServletResponse response) throws IOException {
        SysFileRecycleDto fileInfo = sysFileApi.getFileInfoInRecycle(ossFileId);
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileInfo.getOriginFileName()+"."+fileInfo.getFileSuffix());
        ServletOutputStream outputStream = response.getOutputStream();
        fileService.downLoadObjectToOutputStream(fileInfo.getFileType()?BucketType.secrecyBucket:BucketType.publicBucket,
                fileInfo.getStoragePath(),
                fileInfo.getOssFileId() + "." + fileInfo.getFileSuffix(),outputStream);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
    }

    @ApiOperation(value = "永久删除文件(直接删除文件记录和对象存储的文件,请谨慎使用)")
    @RequestMapping(value = "/deleteFile",method = RequestMethod.GET)
    public BaseResult deleteFile(@RequestParam @ApiParam("文件id")String ossFileId){
        sysFileApi.deleteFile(ossFileId);
        return ResultUtil.success();
    }

    @ApiOperation(value = "异步删除文件（15天内可在文件管理中，恢复）")
    @RequestMapping(value = "/asynDeleteFile",method = RequestMethod.GET)
    public BaseResult asynDeleteFile(@RequestParam @ApiParam("文件id")String ossFileId){
        sysFileApi.asynDeleteFile(ossFileId);
        return ResultUtil.success();
    }

    @ApiOperation(value = "恢复异步删除的文件（超过15天无法恢复）")
    @RequestMapping(value = "/recoveryFileByAsynDelete",method = RequestMethod.GET)
    public BaseResult recoveryFileByAsynDelete(@RequestParam @ApiParam("文件id")String ossFileId){
        sysFileApi.recoveryFileByAsynDelete(ossFileId);
        return ResultUtil.success();
    }

    @ApiOperation(value = "文件确认接口")
    @RequestMapping(value = "/confirmFile",method = RequestMethod.POST)
    public BaseResult confirmFile(@RequestBody List<String> ossFileIds){
        sysFileApi.confirmFile(ossFileIds);
        return ResultUtil.success();
    }


}
